using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 组合攻击策略 - 通过组合模式实现复合攻击
/// </summary>
public class CompositeAttackStrategy : AttackStrategyBase
{
    private List<IAttackStrategy> m_Strategies = new List<IAttackStrategy>();

    public CompositeAttackStrategy(SkillData data)
    {
        AttackData = data;
    }

    /// <summary>
    /// 添加子策略
    /// </summary>
    public void AddStrategy(IAttackStrategy strategy)
    {
        if (strategy != null && !m_Strategies.Contains(strategy))
        {
            m_Strategies.Add(strategy);
            strategy.Owner = Owner;
        }
    }

    /// <summary>
    /// 移除子策略
    /// </summary>
    public void RemoveStrategy(IAttackStrategy strategy)
    {
        if (strategy != null)
        {
            m_Strategies.Remove(strategy);
        }
    }

    /// <summary>
    /// 清空所有子策略
    /// </summary>
    public void ClearStrategies()
    {
        m_Strategies.Clear();
    }

    public override void Execute(Entity target)
    {
        base.Execute(target);

        if (target == null)
        {
            Logger.LogWarning("CompositeAttackStrategy", $"{Owner?.name} 攻击目标无效");
            return;
        }

        // 执行所有子策略
        foreach (var strategy in m_Strategies)
        {
            if (strategy != null && strategy.CheckCondition())
            {
                strategy.Execute(target);
            }
        }

        Logger.Log("CompositeAttackStrategy", $"{Owner?.name} 执行组合攻击，包含 {m_Strategies.Count} 个子策略");
    }

    public override bool CheckCondition()
    {
        if (!base.CheckCondition())
        {
            return false;
        }

        // 至少有一个子策略满足条件
        foreach (var strategy in m_Strategies)
        {
            if (strategy != null && strategy.CheckCondition())
            {
                return true;
            }
        }

        return false;
    }

    public override void Cancel()
    {
        base.Cancel();
        
        // 取消所有子策略
        foreach (var strategy in m_Strategies)
        {
            strategy?.Cancel();
        }
    }

    /// <summary>
    /// 应用效果到目标
    /// </summary>
    public void ApplyEffects(Entity target)
    {
        if (target == null || AttackData == null || AttackData.Effects == null)
        {
            return;
        }

        SkillExecutor.Execute(AttackData.Effects, Owner, target);
    }

    /// <summary>
    /// 获取子策略数量
    /// </summary>
    public int StrategyCount => m_Strategies.Count;
}
